const main = document.getElementById('main');
const progress = document.getElementById('progress');
const columnInput = document.getElementById('columnInput');
const intervalInput = document.getElementById('intervalInput');
const dateInput = document.getElementById('dateInput');

const DEFAULT_DISPLAY_INTERVAL = 10; //默认间隔
const GROUP_MINUTES = 60;
let STEP_MINUTES = 2;

// main.style.gridTemplateColumns = 'repeat(3, 1fr)'; // 默认列数
main.style.gridTemplateColumns = 'repeat(6, 1fr)'; // 默认列数
columnInput.value = 6; // 默认列数

function pad(n) {
    return String(n).padStart(2, '0');
}

function formatTime(date) {
    const year = date.getFullYear();
    const month = pad(date.getMonth() + 1);
    const day = pad(date.getDate());
    const hour = pad(date.getHours());
    const minute = pad(date.getMinutes());
    const monthPart = `${year}-${month}`;
    const datePart = `${year}-${month}-${day}`;
    const timePart = `${datePart}_${hour}-${minute}`;
    return `Screenshots/SS_${monthPart}/SS_${datePart}/SS_${timePart}`; // 这里修改图片路径
}

function formatLabel(date) {
    return date.toLocaleString('zh-CN', {
        // year: 'numeric', month: '2-digit', day: '2-digit',
        hour: '2-digit', minute: '2-digit'
    });
}

// 放大功能相关变量
let currentImgIndex = -1;
let allImgElements = [];
let visibleImgElements = [];

const overlay = document.getElementById('overlay');
const overlayImg = document.getElementById('overlayImg');
const prevBtn = document.getElementById('prevBtn');
const nextBtn = document.getElementById('nextBtn');

function showOverlay(index) {
    visibleImgElements = allImgElements.filter(el => el.style.display !== 'none');
    currentImgIndex = index;
    const src = visibleImgElements[index].querySelector('img').src;
    overlayImg.src = src;
    overlayImg.style.transform = 'scale(1)';
    overlay.style.display = 'flex';
}

function hideOverlay() {
    overlay.style.display = 'none';
    overlayImg.src = '';
    currentImgIndex = -1;
}

function changeImage(step) {
    if (currentImgIndex === -1 || visibleImgElements.length === 0) return;
    const newIndex = currentImgIndex + step;
    if (newIndex >= 0 && newIndex < visibleImgElements.length) {
        showOverlay(newIndex);
    }
}

function handleWheelZoom(e) {
    e.preventDefault();
    let scale = parseFloat(overlayImg.style.transform.replace('scale(', '').replace(')', '')) || 1;
    scale += e.deltaY < 0 ? 0.1 : -0.1;
    scale = Math.max(0.5, Math.min(5, scale));
    overlayImg.style.transform = `scale(${scale.toFixed(2)})`;
}

overlay.addEventListener('click', (e) => {
    if (e.target === overlay) hideOverlay();
});

overlay.addEventListener('wheel', handleWheelZoom);
prevBtn.addEventListener('click', () => changeImage(-1));
nextBtn.addEventListener('click', () => changeImage(1));

document.addEventListener('keydown', (e) => {
    if (overlay.style.display !== 'flex') return;
    if (e.key === 'ArrowLeft') changeImage(-1);
    if (e.key === 'ArrowRight') changeImage(1);
    if (e.key === 'Escape') hideOverlay();
});

function createImgElement(src, hour, minute) {
    const container = document.createElement('div');
    container.style.position = 'relative';

    const img = document.createElement('img');
    img.loading = 'lazy';
    img.src = src;
    img.dataset.minute = minute;
    container.appendChild(img);

    const label = document.createElement('span');
    label.textContent = `${pad(hour)}:${pad(minute)}`;
    label.style.position = 'absolute';
    label.style.right = '4px';
    label.style.bottom = '4px';
    label.style.backgroundColor = 'rgba(0,0,0,0.5)';
    label.style.color = 'white';
    label.style.fontSize = '14px';
    label.style.padding = '2px 4px';
    label.style.borderRadius = '3px';
    container.appendChild(label);

    container.addEventListener('click', () => {
        visibleImgElements = allImgElements.filter(el => el.style.display !== 'none');
        const index = visibleImgElements.indexOf(container);
        if (index !== -1) showOverlay(index);
    });

    allImgElements.push(container);
    return container;
}

function checkImageExists(src) {
    return new Promise(resolve => {
        const img = new Image();
        img.src = src;
        img.onload = () => resolve(true);
        img.onerror = () => resolve(false);
    });
}

columnInput.addEventListener('change', () => {
    const col = Math.max(1, parseInt(columnInput.value) || 3);
    main.style.gridTemplateColumns = `repeat(${col}, 1fr)`;
});

function updateVisibleImages(interval) {
    const containers = main.querySelectorAll('div');
    containers.forEach(div => {
        const img = div.querySelector('img');
        if (!img) return;
        const minute = parseInt(img.dataset.minute);
        div.style.display = (minute % interval === 0) ? '' : 'none';
    });
}

intervalInput.addEventListener('change', () => {
    const val = parseInt(intervalInput.value);
    if (val && val > 0 && val <= 60) {
        updateVisibleImages(val);
    }
});

async function loadImages(startTime, endTime) {
    const fixedDateDiv = document.getElementById('fixedDate');
    fixedDateDiv.textContent = startTime.toLocaleDateString('zh-CN');    
    
    main.innerHTML = '';
    allImgElements = [];
    visibleImgElements = [];
    progress.textContent = '加载中...';

    let completedSteps = 0;
    let currentGroupStart = new Date(startTime);
    currentGroupStart.setMinutes(0, 0, 0);

    while (currentGroupStart < endTime) {
        let groupHasImages = false;
        const groupImages = [];

        for (let m = 0; m < 60; m += STEP_MINUTES) {
            const t = new Date(currentGroupStart);
            t.setMinutes(m);
            if (t >= endTime) break;

            const src = formatTime(t) + '.jpg';
            const exists = await checkImageExists(src);
            if (exists) {
                groupHasImages = true;
                const imgElem = createImgElement(src, t.getHours(), t.getMinutes());
                groupImages.push(imgElem);
                completedSteps++;
            }
        }

        if (groupHasImages) {
            const title = document.createElement('h4');
            title.textContent = formatLabel(currentGroupStart);
            main.appendChild(title);
            groupImages.forEach(imgElem => main.appendChild(imgElem));
        }

        currentGroupStart = new Date(currentGroupStart.getTime() + GROUP_MINUTES * 60 * 1000);
        progress.textContent = `加载中：${completedSteps} 张图片`;
    }

    progress.textContent = `加载完成，共处理 ${completedSteps} 张图片`;

    const interval = parseInt(intervalInput.value) || DEFAULT_DISPLAY_INTERVAL;
    updateVisibleImages(interval);
}

// 06-21 固定日期测试备份
window.addEventListener('DOMContentLoaded', () => {
    const now = new Date();
    now.setSeconds(0, 0);
    now.setMinutes(now.getMinutes() - (now.getMinutes() % STEP_MINUTES));

    const todayStart = new Date(now);
    todayStart.setHours(0, 0, 0, 0);  // 今天0点

    loadImages(todayStart, now);
});


dateInput.addEventListener('change', () => {
    const selected = dateInput.value;
    if (!selected) return;

    const start = new Date(selected + 'T00:00:00');
    const end = new Date(selected + 'T23:59:59');
    loadImages(start, end);
});

